<?php
/**
 * Class WithdrawalApply
 * Desc  提现申请
 * Create on 2021/9/2 10:51
 * Create by wangyafang
 */

namespace app\api\controller\xyb;


use app\admin\model\xyb\system\Config;
use app\api\model\xyb\Wallets;
use app\api\service\UsersService;
use think\Db;

class WithdrawalApply extends Base
{
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\api\model\xyb\AgentWithdrawalApply();
    }


    public function submit(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        /*提现金额*/
        if(!$real_amount = (float)$this->request->param('amount')){
            $this->error('请输入提现金额');
        }

        $users = $this->getAuthUsers();
        $users_agent = UsersService::getCommunityWhereUsersLocated($users->id);

        $wallets = UsersService::alculateUserWithdrawalRevenue($users_agent->users_identity, $users->id, $users_agent->agent_id);
        $systemConfigModel = new Config();
        $withdrawal_pay_method = $systemConfigModel::getAgentConfig(1,'withdrawal_pay_method');
        $min_withdrawal_amount = (float)$systemConfigModel::getAgentConfig($users_agent->agent_id,'min_withdrawal_amount');
        $service_charge = (float)$systemConfigModel::getAgentConfig($users_agent->agent_id,'service_charge');
        if(!$wallets || ($wallets['total_withdrawal_amount'] < $real_amount)) {
            $this->error('余额不足');
        }
        if($real_amount < $min_withdrawal_amount){
            $this->error('提现金额不能小于'.$min_withdrawal_amount);
        }
        if($real_amount > $wallets['total_withdrawal_amount']){
            $this->error('提现金额不能大于'.$wallets['total_withdrawal_amount']);
        }
        $arrival_amount = ($real_amount * ($service_charge  / 100));
        if($this->model->where(['user_id'=>$users->id, 'status'=>0])->find()) {
            $this->error('已有提现申请');
        }
        $walletsModel = new Wallets();
        $forms = [
            'user_id'               => $users->id,
            'amount'                => $real_amount,
            'server_fee'            => $arrival_amount ,
            'arrival_amount'        => bcsub($real_amount, $arrival_amount,2),
            'withdrawal_pay_method' => $withdrawal_pay_method,
        ];
        $rider_real_amount = 0;
        $agent_real_amount = 0;
        Db::startTrans();
        try {
            $rider_buckle = $agent_buckle = 0;
            /*先扣跑腿的钱*/
            $rider_withdrawal_amount = (float)$wallets['rider_withdrawal_amount'];

            /*跑腿费用 大于等于 提现金额；*/
            if($rider_withdrawal_amount >= $real_amount) {
                $rider_real_amount = $real_amount ;
                $walletsModel->save(['can_withdrawal_amount' => ($rider_withdrawal_amount - $real_amount)], ['user_id' => $users->id, 'type' => 1]);
                $real_amount = 0;
            } else {
                $real_amount = ($real_amount - $rider_withdrawal_amount);
                $rider_real_amount = $rider_withdrawal_amount;
                $walletsModel->save(['can_withdrawal_amount' => 0], ['user_id' => $users->id, 'type' => 1]);
            }
            if($real_amount && in_array($users_agent->users_identity, [3, 4])){
                $agent_withdrawal_amount = (float)$wallets['agent_withdrawal_amount'];
                if($real_amount > $agent_withdrawal_amount){
                    $this->error('提现金额不能大于'.$users_agent['total_withdrawal_amount']);
                }
                $agent_real_amount = $real_amount;
                $agent_buckle = ($agent_withdrawal_amount - $real_amount);
                $walletsModel->save(['can_withdrawal_amount' => ($agent_buckle >= 0 ? $agent_buckle : 0)], ['user_id' => $users_agent->agent_id, 'type' => 2]);
            }
            $forms['rider_amount'] = $rider_real_amount;
            $forms['agent_amount'] = $agent_real_amount;
            $this->model->save($forms);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    public function withdrawal_list()
    {
        $users = $this->getAuthUsers();
        $where['user_id'] = array('eq', $users->id);
        $list = $this->model->where($where)->order('id asc')->select();

        $_list = [];

        $date = [];

        foreach ($list as $key) {

            $time = date('Y-m', strtotime($key['createtime']));

            $date[] = strtotime($time);
        }
        $date = array_count_values($date);

        foreach ($date as $k => $v) {
            $_list[$v]['year'] = date('Y', $k);
            $_list[$v]['mon'] = date('m', $k);
            $_list[$v]['daysInMonth'] = date('t', $k);
            $_list[$v]['list'] = $this->model->where('user_id', $users->id)->where('createtime', 'between', [$k, $k + 86400 * $_list[$v]['daysInMonth']])->select();
        }
        usort($_list, function ($a, $b) {
            return $b['year'] <=> $a['year'];
        });
        $this->success('操作成功', $_list);
    }

    /**
     * desc:代理员提现明细
     */
    public function withdrawal_list_bak()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $where['user_id'] = $users->id;
        if(isset($param['status'])) {
            $where['status'] = $this->request->param('status');
        }
        $data = $this->model->getList($this->model,$where,'amount,createtime,status,reject_reason,arrival_amount,server_fee','id desc');
        $this->success('请求成功',$data);
    }

    public function submit_bak(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->param();
        $real_amount = $param['real_amount'];

        $user_id = $this->auth->id;
        $walletsModel = new Wallets();
        $walletsObj = $walletsModel->where([
            'user_id'=>$user_id,
            'type'=>2,
            'status'=>'normal',
        ])->find();

        if(!$walletsObj || ($walletsObj['can_withdrawal_amount'] < $param['amount'])) {
            $this->error('余额不足');
        }

        if($this->model->where([
            'user_id'=>$user_id,
            'status'=>0,
            'app_plat'=>$param['app_plat'],
        ])->find()) {
            $this->error('已有提现申请');
        }

        $systemConfigModel = new Config();
        $withdrawal_pay_method = $systemConfigModel->where('id',1)->value('withdrawal_pay_method');
        Db::startTrans();
        try {
            $this->model->save([
                'user_id'=>$user_id,
                'amount'=>$param['amount'],
                'server_fee'=>bcsub($param['amount'],$real_amount,2),
                'arrival_amount'=>$real_amount,
                'app_plat'=>$param['app_plat'],
                'withdrawal_pay_method'=>$withdrawal_pay_method,
            ]);
            $walletsModel->save([
                'can_withdrawal_amount'  => bcsub($walletsObj['can_withdrawal_amount'],$param['amount'],2),
            ],['id' => $walletsObj['id']]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * desc:代理员提现明细
     */
    public function agent_withdrawal_list_bak()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $where['user_id'] = array('eq',$this->auth->id);
        if(isset($param['status'])) {
            $where['status'] = $this->request->param('status');
        }
        $where['app_plat'] = $this->request->param('app_plat');
        $data = $this->model->getList($this->model,$where,'amount,createtime,status,reject_reason,arrival_amount','id desc');
        $this->success('请求成功',$data);
    }
}